<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- 基础布局 -->
      <PageTools show-before>
        <!-- 工具栏 -->
        <span slot="before">共{{ page.total }}条记录</span>

        <template slot="after">
          <el-button
            size="small"
            type="danger"
            @click="exportData"
          >简单表头导出</el-button>
          <el-button
            size="small"
            type="info"
            @click="exportData(true)"
          >复杂表头导出</el-button>
          <el-button
            size="small"
            type="success"
            @click="$router.push('/import')"
          >excel导入</el-button>
          <el-button
            size="small"
            type="primary"
            :disabled="!checkPermission('add-user')"
            @click="showDialog = true"
          >新增员工</el-button>
        </template>
      </PageTools>

      <el-card>
        <!-- 表格 -->
        <el-table v-loading="loading" :data="list" stripe>
          <el-table-column label="序号" sortable="" type="index" />
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column label="头像" sortable="" prop="staffPhoto">
            <template v-slot="{ row }">
              <img
                v-imgError="require('@/assets/common/meizi.webp')"
                :src="row.staffPhoto"
                style="
                  border-radius: 50%;
                  width: 100px;
                  height: 100px;
                  padding: 10px;
                "
                alt=""
                @click="showQrCode(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column label="手机号" sortable="" prop="mobile" />
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <el-table-column
            label="聘用形式"
            sortable=""
            prop="formOfEmployment"
            :formatter="formatEmployment"
          />
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <el-table-column label="入职时间" sortable="" prop="timeOfEntry">
            <!-- 传入插槽 -->
            <template v-slot="{ row }">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" sortable="" prop="enableState">
            <template v-slot="{ row }">
              <el-switch
                :value="row.enableState === 1"
                active-color="#13ce66"
                inactive-color="#ff4949"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="280" sortable="">
            <template v-slot="{ row }">
              <el-button
                type="text"
                size="small"
                @click="$router.push(`/employees/detail/${row.id}`)"
              >查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button
                type="text"
                size="small"
                @click="editRole(row.id)"
              >角色</el-button>
              <el-button
                type="text"
                size="small"
                :disabled="!checkPermission('del-user')"
                @click="deleteEmployee(row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-row type="flex" justify="end" align="middle" style="height: 80px">
          <!-- 分页 -->
          <el-pagination
            layout="prev,pager,next"
            background
            :total="page.total"
            :surrent-page="page.page"
            :page-size="page.size"
            @current-change="changePage"
          />
        </el-row>
      </el-card>
    </div>

    <!-- 添加员工弹出层 -->
    <AddEmployee :show-dialog.sync="showDialog" />

    <!-- 二维码弹出层 -->
    <el-dialog title="扫码预览" :visible.sync="showCodeDialog">
      <el-row type="flex" justify="center">
        <canvas ref="myCanvas" />
      </el-row>
    </el-dialog>

    <!-- 角色分配弹出层 -->
    <AssignRole ref="assignRole" :show-role-dialog.sync="showRoleDialog" :user-id="userId" />
  </div>
</template>

<script>
import { getEmployeeList, delEmployee } from '@/api/employees'
import EmployeeEnum from '@/api/constant/employees' // 引入枚举对象
import AddEmployee from './components/add-employee'
import AssignRole from './components/assign-role'
import { formatDate } from '@/filters'
import QrCode from 'qrcode' // 二维码插件
export default {
  components: {
    AddEmployee,
    AssignRole
  },
  data() {
    return {
      EmployeeEnum,
      page: {
        page: 1,
        size: 10,
        total: 0
      },

      list: [],
      loading: false,
      showDialog: false, // 显示添加员工弹出层
      showCodeDialog: false, // 显示二维码弹层
      showRoleDialog: false, // 角色分配弹出此显示
      userId: null // 记录当前当前点击的用户id
    }
  },

  created() {
    this.getEmployeeList()
  },
  methods: {
    // 获取员工列表
    async getEmployeeList() {
      this.loading = true
      const { total, rows } = await getEmployeeList(this.page)
      this.page.total = total
      this.list = rows
      await new Promise((resolve) => setTimeout(() => resolve(), 500))
      this.loading = false
    },

    // 切换页码
    changePage(newPage) {
      this.page.page = newPage
      this.getEmployeeList()
    },

    // 聘用格式化
    formatEmployment(row, column, cellValue, index) {
      //   可以通过row获取对应的值
      // 也可以直接用cellValue, 需要配置prop属性
      const obj = this.EmployeeEnum.hireType.find(
        (item) => item.id + '' === cellValue + ''
      )
      return obj ? obj.value : '未知'
    },

    // 删除员工
    async deleteEmployee(id) {
      try {
        await this.$confirm('确定要删除该员工吗？')
        await delEmployee(id)
        this.getEmployeeList()
        this.$message.success('删除成功！')
        if (this.list.length === 1) {
          this.page.page--
          this.getEmployeeList()
        }
      } catch (error) {
        console.log(error)
      }
    },

    // 导出Excel
    exportData(isComplex) {
      const headers = {
        姓名: 'username',
        手机号: 'mobile',
        入职日期: 'timeOfEntry',
        聘用形式: 'formOfEmployment',
        转正日期: 'correctionTime',
        工号: 'workNumber',
        部门: 'departmentName'
      }
      // 懒加载
      import('@/vendor/Export2Excel').then(async(excel) => {
        // 此时表示该模块已经导入
        const { rows } = await getEmployeeList({
          page: 1,
          size: this.page.total
        })
        // rows: [{},{},{}] => [[],[],[]]

        const data = this.formatJson(headers, rows)
        const multiHeader = isComplex
          ? [['姓名', '主要信息', '', '', '', '', '部门']]
          : []
        const merges = isComplex ? ['A1:A2', 'B1:F1', 'G1:G2'] : []
        excel.export_json_to_excel({
          header: Object.keys(headers), // 表头 必填
          multiHeader, // 复杂表头
          merges, // 合并行列
          data, // 具体数据 必填
          filename: 'iHrm人力资源用户表', // 非必填
          autoWidth: true, // 非必填
          bookType: 'xlsx' // 非必填
        })
      })
    },

    // 格式化JSON数据
    // rows: [{},{},{}] => [[],[],[]]
    formatJson(headers, rows) {
      // 对第一层的数组进行遍历
      return rows.map((item) => {
        return Object.values(headers).map((value) => {
          // 此时value就是字段名
          // 需要针对几个字段进行处理
          if (value === 'formOfEmployment') {
            //   如多字段是 '聘用形式' 时, 要把它转化成真实情景
            const obj = this.EmployeeEnum.hireType.find(
              (o) => o.id + '' === item[value] + ''
            )

            return obj ? obj.value : '未知'
          } else if (value === 'timeOfEntry' || value === 'correctionTime') {
            //   字段为日期时, 格式化日期
            return formatDate(item[value])
          }

          return item[value]
        })
      })
    },

    // 头像二维码
    showQrCode(url) {
      if (url) {
        // 只有当有url地址的情况下, 才弹出二维码
        this.showCodeDialog = true // 数据更新了 但是我的弹层会立刻出现吗 ？页面的渲染是异步的！！！！
        // 有一个方法可以在上一次数据更新完毕，页面渲染完毕之后
        this.$nextTick(() => {
          // 此时可以确认已经有ref对象了
          QrCode.toCanvas(this.$refs.myCanvas, url) // 将地址转化成二维码
          // 如果转化的二维码后面信息 是一个地址的话 就会跳转到该地址 如果不是地址就会显示内容
        })
      } else {
        this.$message.warning('您还未上传头像！')
      }
    },

    // 角色管理
    async editRole(id) {
      this.userId = id // 记录当前点击的用户id
      // 可以通过此id
      await this.$refs.assignRole.getUserDetailById(id) // 调用子组件方法
      this.showRoleDialog = true // 弹出窗口
    }
  }
}
</script>

<style>
</style>
